From 4672a0846297cea8184c2c3f52b4dc05f9c79fd2 Mon Sep 17 00:00:00 2001
From: Ilion Beyst <ilion.beyst@gmail.com>
Date: Sat, 6 Aug 2022 15:23:02 +0200
Subject: introduce ApiClient

---
 web/pw-server/src/routes/bots/[bot_name].svelte | 41 +++++++++----------------
 1 file changed, 15 insertions(+), 26 deletions(-)

(limited to 'web/pw-server/src/routes/bots/[bot_name].svelte')

diff --git a/web/pw-server/src/routes/bots/[bot_name].svelte b/web/pw-server/src/routes/bots/[bot_name].svelte
index 48aef21..d110e4b 100644
--- a/web/pw-server/src/routes/bots/[bot_name].svelte
+++ b/web/pw-server/src/routes/bots/[bot_name].svelte
@@ -1,27 +1,16 @@
 <script lang="ts" context="module">
-  import { get_session_token } from "$lib/auth";
+  import { ApiClient } from "$lib/api_client";
 
   export async function load({ params, fetch }) {
-    const token = get_session_token();
-    const res = await fetch(`/api/bots/${params["bot_name"]}`, {
-      headers: {
-        "Content-Type": "application/json",
-        Authorization: `Bearer ${token}`,
-      },
-    });
-
-    const matches_res = await fetch(`/api/matches?bot=${params["bot_name"]}`, {
-      headers: {
-        "Content-Type": "application/json",
-        Authorization: `Bearer ${token}`,
-      },
-    });
-
-
-    if (res.ok && matches_res.ok) {
-      const { bot, owner, versions } = await res.json();
-      const matches = await matches_res.json();
-      // sort most recent first
+    const apiClient = new ApiClient(fetch);
+
+    try {
+      const [botData, matches] = await Promise.all([
+        apiClient.get(`/api/bots/${params["bot_name"]}`),
+        apiClient.get("/api/matches", { bot: params["bot_name"] }),
+      ]);
+
+      const { bot, owner, versions } = botData;
       versions.sort((a: string, b: string) =>
         dayjs(a["created_at"]).isAfter(b["created_at"]) ? -1 : 1
       );
@@ -33,12 +22,12 @@
           matches,
         },
       };
+    } catch (error) {
+      return {
+        status: error.status,
+        error: error,
+      };
     }
-
-    return {
-      status: res.status,
-      error: new Error("Could not find bot"),
-    };
   }
 </script>
 
-- 
cgit v1.2.3

